// mock/permission.ts

// 模拟延迟
const waitTime = (time: number = 100) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(true);
        }, time);
    });
};

// 生成模拟权限数据
const generateMockPermissionData = (): any[] => {
    const data = [];

    for (let i = 1; i <= 50; i++) {
        const menuType = i % 3; // 0: 菜单, 1: 菜单, 2: 按钮/权限
        data.push({
            id: `perm_${i}`,
            name: `权限${i}`,
            menuType: menuType,
            menuType_dictText: menuType === 0 ? '菜单' : menuType === 1 ? '菜单' : '按钮/权限',
            perms: `perm:${i}`,
            url: `/perm/${i}`,
            component: `Perm${i}Component`,
            permsType: 1, // 假设默认为 1
            sortNo: i,
            status: 1, // 假设默认为 1
            description: `这是权限 ${i} 的描述`,
            createTime: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toISOString(),
            updateTime: new Date(Date.now() - Math.floor(Math.random() * 5000000000)).toISOString(),
            // ... 其他可能的字段
        });
    }

    return data;
};

let mockPermissions = generateMockPermissionData();

export default {
    // 获取权限列表
    'GET /sys/permission/list': async (req: any, res: any) => {
        await waitTime(500);

        const { current = 1, pageSize = 10, name, perms, menuType } = req.query;

        let filteredPermissions = [...mockPermissions];

        // 应用查询条件
        if (name) {
            filteredPermissions = filteredPermissions.filter(p => p.name.includes(name));
        }
        if (perms) {
            filteredPermissions = filteredPermissions.filter(p => p.perms.includes(perms));
        }
        if (menuType !== undefined && menuType !== '') {
            filteredPermissions = filteredPermissions.filter(p => p.menuType.toString() === menuType);
        }

        // 分页
        const start = (parseInt(current) - 1) * parseInt(pageSize);
        const end = start + parseInt(pageSize);
        const paginatedData = filteredPermissions.slice(start, end);

        res.json({
            success: true,
            message: '获取成功',
            result: {
                records: paginatedData,
                total: filteredPermissions.length,
            },
        });
    },

    // 删除单个权限
    'PUT /sys/permission/delete': async (req: any, res: any) => {
        await waitTime(300);
        const { id } = req.query;

        const index = mockPermissions.findIndex(p => p.id === id);
        if (index > -1) {
            mockPermissions.splice(index, 1);
            res.json({
                success: true,
                message: '删除成功',
            });
        } else {
            res.status(404).json({
                success: false,
                message: '未找到权限',
            });
        }
    },

    // 批量删除权限
    'PUT /sys/permission/deleteBatch': async (req: any, res: any) => {
        await waitTime(500);
        const { ids } = req.query;
        const idList = ids.split(',');

        const initialLength = mockPermissions.length;
        idList.forEach((id: string) => {
            const index = mockPermissions.findIndex(p => p.id === id);
            if (index > -1) {
                mockPermissions.splice(index, 1);
            }
        });
        const deletedCount = initialLength - mockPermissions.length;

        res.json({
            success: deletedCount > 0,
            message: `成功删除 ${deletedCount} 条记录`,
        });
    },

    // 获取权限信息 (用于编辑/详情)
    'GET /sys/permission/queryById': async (req: any, res: any) => {
        await waitTime(300);
        const { id } = req.params;
        const permission = mockPermissions.find(p => p.id === id);

        if (permission) {
            res.json({
                success: true,
                message: '获取成功',
                result: permission,
            });
        } else {
            res.status(404).json({
                success: false,
                message: '未找到权限',
            });
        }
    },

    // 添加权限
    'POST /sys/permission/add': async (req: any, res: any) => {
        await waitTime(500);
        const data = req.body;

        // 检查唯一性 (Mock)
        if (mockPermissions.some(p => p.perms === data.perms)) {
            res.status(400).json({
                success: false,
                message: '权限编码已存在',
            });
            return;
        }

        const newPermission = {
            ...data,
            id: `perm_${mockPermissions.length + 1}`, // Mock ID 生成
            createTime: new Date().toISOString(),
            updateTime: new Date().toISOString(),
        };
        mockPermissions.push(newPermission);

        res.json({
            success: true,
            message: '新增成功',
            result: newPermission,
        });
    },

    // 编辑权限
    'PUT /sys/permission/edit': async (req: any, res: any) => {
        await waitTime(500);
        const data = req.body;
        const index = mockPermissions.findIndex(p => p.id === data.id);

        if (index > -1) {
            // 检查唯一性 (排除自己) (Mock)
            if (mockPermissions.some((p, i) => p.perms === data.perms && i !== index)) {
                res.status(400).json({
                    success: false,
                    message: '权限编码已存在',
                });
                return;
            }

            mockPermissions[index] = { ...mockPermissions[index], ...data, updateTime: new Date().toISOString() };

            res.json({
                success: true,
                message: '编辑成功',
                result: mockPermissions[index],
            });
        } else {
            res.status(404).json({
                success: false,
                message: '未找到权限',
            });
        }
    },

    // 获取权限规则列表 (如果需要)
    'GET /sys/permission/rule/list': async (req: any, res: any) => {
        await waitTime(500);
        const { permissionId } = req.query; // 假设根据权限ID查询规则

        // Mock: 返回一些固定的规则
        const mockRules = [
            { id: `rule_${permissionId}_1`, name: `规则1`, condition: 'condition1', description: '规则1描述' },
            { id: `rule_${permissionId}_2`, name: `规则2`, condition: 'condition2', description: '规则2描述' },
        ];

        res.json({
            success: true,
            message: '获取成功',
            result: mockRules,
        });
    },
};